import Vue from "vue";
import Vuex from "vuex";
import app from "./modules/app";
import { Loading, Message } from "element-ui";
import api from "@/api/api.js";
import router from "@/router/index.js";

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    token: "",
    load: null,
    userInfo: {},
    userName: "",
    routers: [],
    execute: null,
    tableSize: "small",
    isSecuritySettings:0 // 是否设置密保
  },
  mutations: {
    setToken(state, token) {
      state.token = token;
    },
    setUserinfo: (state, data) => {
      state.userInfo = data;
    },
    setUserName: (state, data) => {
      state.userName = data;
    },
    isSecuritySettings: (state, data) => {
      state.isSecuritySettings = data;
    },
    OpenLoading: (state) => {
      state.load = Loading.service(
        {
          text: "loading...",
          spinner: "el-icon-loading",
          background: "rgba(143, 143, 143, 0.301)",
        }
      );
    },
    setRoutes: (state, router) => {
      state.routers = router;
    },
    CloseLoading: (state) => {
      state.load.close();
    }
  },
  modules: {
    app
  },
  getters: {
    sidebar: state => state.app.sidebar,
    userInfo: state => state.userInfo,
    userName: state => state.userName,
    tableSize: state => state.tableSize,
    routers: state => state.routers,
  },
  actions:{
    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        api.common.getUser()
          .then((res) => {
            if (res.code === 200) {
              commit("setUserinfo", res.data);
              commit("setUserName", res.data.userName);
              commit("isSecuritySettings",res.data.isSecuritySettings);
              if(res.data.isSecuritySettings==0){
                router.push({path:"/completeUserInfo"})
              }
              resolve(res)
            }
          })
          .catch(err => {
            Message.error(err);
            commit("setToken", "");
            localStorage.removeItem("token");
            router.push({ path: "/login" });
            reject(err)
          });
      })

    },
  }
});

export default store;
